package com.bruce.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 日期公共类
 *
 * @author LiXiaolong
 * @version 1.0
 * @since 2013-5-3 上午10:19:35
 */
public class DateUtil {
    /**
     * yyyy-MM-dd
     */
    public static final String FORMAT_ONE = "yyyy-MM-dd";
    /**
     *  yyyy-MM-dd HH:mm
     */
    public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";
    /**
     * yyyy-MM-dd HH:mm:ss
     */
    public static final String FORMAT_THREE = "yyyy-MM-dd HH:mm:ss";

    public static final String FORMAT_FOUR = "yyyy-MM-dd HH:mm:ss";

    private static final int today = 1;
    private static final int yesterday = 2;
    private static final int beforeYesterday = 3;
    private static final int lastYear = 4;

    private static final Locale defLocale = Locale.getDefault();

    /**
     * 将从服务器拿回的日期格式化
     *
     * @param date_str 服务器日期字符串
     * @return 格式化日期字符串
     */
    public static String formatServerDate(String date_str) {
        if (!EmptyUtil.isEmpty(date_str)) {
            if (date_str.contains("-") && !date_str.contains(":")) {
                return date_str.trim() + " 00:00:00";
            } else {
                String[] date = date_str.split(" ");
                if (date.length == 2) {
                    String d = date[0].trim();
                    String t = date[1].trim();
                    return d + " " + t;
                } else {
                    return date_str;
                }
            }
        }
        return null;
    }

    /**
     * 格式化当前时间
     *
     * @param format 时间格式
     * @return 格式化日期字符串
     */
    public static String formatCurrDate(String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format, defLocale);
        Date curDate = new Date();// 获取当前时间
        return formatter.format(curDate);
    }

    public static Date parseDate(String strDate) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_THREE, defLocale);
        return formatter.parse(strDate);
    }

    /**
     * 格式化时间字符串
     *
     * @param dateStr 时间字符串
     * @param format  时间格式
     * @return 格式化后的时间
     */
    public static String formatDate(String dateStr, String format) {
        if (!EmptyUtil.isEmpty(dateStr)) {
            if (dateStr.contains(".")) {
                dateStr = dateStr.substring(0, dateStr.indexOf("."));
            }
            String newData;
            SimpleDateFormat sd = new SimpleDateFormat(FORMAT_THREE, Locale.getDefault());
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
            try {
                Date date = sd.parse(dateStr);
                newData = sdf.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
                return dateStr;
            }
            return newData;
        }
        return null;
    }

    public static long formatDateStrForLong(String dateStr) {
        long newData = 0;
        if (EmptyUtil.isEmpty(dateStr)) {
            return newData;
        }
        if (dateStr.contains(".")) {
            dateStr = dateStr.substring(0, dateStr.indexOf("."));
        }
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", defLocale);
        try {
            Date date = sd.parse(dateStr);
            newData = date.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            newData = 0;
        }
        return newData;
    }

    /**
     * 格式化毫秒时间
     *
     * @param dateLong 毫秒时间
     * @param format   时间格式
     * @return 格式化后的时间
     */
    public static String formatDate(Long dateLong, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format, defLocale);
        Date curDate = new Date(dateLong);// 获取当前时间
        return formatter.format(curDate);
    }

//    /**
//     * 当前时间与给定的时间是否大于给定的时间之差
//     *
//     * @param time 给定的时间
//     * @param disc 两个时间之差
//     * @return true 大于； false 小于
//     */
//    public static boolean IsMoreThanDisc(long time, long disc) {
//        Date date = new Date();
//        long currTime = date.getTime();
//        return currTime - time >= disc;
//    }

    /**
     * 判断当前时间是否在推送时间段内
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return true:在时间段内，false：没有在时间段内
     */
    public static boolean isInTimePeriod(int start, int end) {
        try {
            Date currDate = new Date();
            long currTime = currDate.getTime();
            String currDay = formatDate(currTime, "yyyy-MM-dd");
            String strTime = start + ":00:00";
            String endTime = end + ":00:00";
            if (start < 10) {
                strTime = "0" + start + ":00:00";
            }
            if (end < 10) {
                endTime = "0" + end + ":00:00";
            }
            if (end >= 23) {
                endTime = end + ":59:59";
            }

            String strDate = currDay + " " + strTime;
            String endDate = currDay + " " + endTime;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", defLocale);
            Date sDate = sdf.parse(strDate);
            Date eDate = sdf.parse(endDate);
            long sTime = sDate.getTime();
            long eTime = eDate.getTime();
            if (currTime >= sTime && currTime <= eTime) {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

//    /**
//     * 格式化相对时间（几分钟前，几小时前，几天前）
//     *
//     * @param dateStr 日期时间字符串
//     * @return 格式化相对时间
//     */
//    public static String FormatRelDate(String dateStr) {
//        if (dateStr != null && dateStr.contains(".")) {
//            dateStr = dateStr.replace(".", ":");
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            Date date = sdf.parse(dateStr);
//            return formatRelativeDate(date);
//        } catch (ParseException e) {
//            e.printStackTrace();
//            return dateStr;
//        }
//    }
//
//
//    public static String FormatRelDate(Long time) {
//        Date date = new Date(time);
//        return formatRelativeDate(date);
//    }
//
//    private static String formatRelativeDate(Date date) {
//        final long one_minute = 60000L;// 1分钟（毫秒数）
//        final long one_hour = 3600000L;// 1小时（毫秒数）
//        final long one_day = 86400000L;// 1天（毫秒数）86745520
//
//        long delta = new Date().getTime() - date.getTime();
//
//        if (delta < one_hour) {
//            long minutes = delta / one_minute;
//            return (minutes <= 0 ? 1 : minutes) + "分钟前";
//        }
//
//        if (delta < one_day) {
//            long hours = delta / one_hour;
//            return (hours <= 0 ? 1 : hours) + "小时前";
//        }
//
//        if (delta < one_day * 2L) {
//            return "昨天";
//        }
//
//        if (delta < one_day * 3L) {
//            long days = delta / one_day;
//            return (days <= 0 ? 1 : days) + "天前";
//        } else {
//            return FormatDate(date, "yyyy-MM-dd");
//        }
//    }

//    public static String formatChatDate(long times) {
//        // 时间显示规则：当天信息显示具体时间“00：00”，其余信息显示“月份-日期”，隔年的消息显示“年份-月份-日期”
//        Calendar today = Calendar.getInstance();
//        today.set(Calendar.HOUR_OF_DAY, 0);
//        today.set(Calendar.MINUTE, 0);
//        today.set(Calendar.SECOND, 0);
//
//
//        Calendar thisYear = Calendar.getInstance();
//        thisYear.set(Calendar.MONTH, 0);
//        thisYear.set(Calendar.HOUR_OF_DAY, 0);
//        thisYear.set(Calendar.MINUTE, 0);
//        thisYear.set(Calendar.SECOND, 0);
//
//        Calendar c = Calendar.getInstance();
//        c.setTimeInMillis(times);
//        SimpleDateFormat sdf;
//        if (c.before(thisYear)) {
//            sdf = new SimpleDateFormat("yyyy-MM-dd");
//        } else if (c.before(today)) {
//            sdf = new SimpleDateFormat("MM-dd");
//        } else {
//            sdf = new SimpleDateFormat("HH:mm");
//        }
//        return sdf.format(new Date(times));
//    }

    public static String getMonthByChina(int month) {
        switch (month) {
            case 1:
                return "一月";
            case 2:
                return "二月";
            case 3:
                return "三月";
            case 4:
                return "四月";
            case 5:
                return "五月";
            case 6:
                return "六月";
            case 7:
                return "七月";
            case 8:
                return "八月";
            case 9:
                return "九月";
            case 10:
                return "十月";
            case 11:
                return "十一月";
            case 12:
                return "十二月";
        }
        return null;
    }

    public static String formatBirthday(String birthday) {
        if (EmptyUtil.isEmpty(birthday)) {
            return "";
        } else {
            if (birthday.length() >= 10) {
                String y = birthday.substring(0, 4);
                String m = birthday.substring(5, 7);
                String d = birthday.substring(8, 10);
                return y + "年" + m + "月" + d + "日";
            }
            return birthday;
        }
    }

    public static String formatRefreshTime(long time) {
        Date date = new Date(time);
        String fromatedDate = null;
        int type = judgeDate(date);
        switch (type) {
            case today:
                fromatedDate = fromatDate(date, "HH:mm");
                break;
            case yesterday:
                fromatedDate = String.format("昨天 %1$s", fromatDate(date, "HH:mm"));
                break;
            case beforeYesterday:
                fromatedDate = fromatDate(date, "MM-dd");
                break;
            case lastYear:
                fromatedDate = fromatDate(date, "yyyy-MM-dd");
                break;
        }
        return fromatedDate;
    }

    /**
     * 格式化相对时间【1小时以内（不含1小时），显示**分钟前，24小时以内（不含24小时），显示**小时前，1天以上（含1天），显示YYYY-MM-DD；】
     *
     * @param dateStr 时间字符串
     * @return 格式化后的时间字符串
     */
    public static String formatReleaseDate(String dateStr) {
        if (EmptyUtil.isEmpty(dateStr)) {
            return "";
        }
        if (dateStr.contains(".")) {
            dateStr = dateStr.substring(0, dateStr.indexOf("."));
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_THREE, defLocale);
            Date date = sdf.parse(dateStr);
            if (date == null) {
                return dateStr;
            }
            long delta = new Date().getTime() - date.getTime();
            if (delta < 60L * 60000L) {
                long minutes = (delta / 1000L) / 60L;
                return (minutes <= 0 ? 1 : minutes) + "分钟前";
            }
            if (delta < 24L * 3600000L) {
                long hours = ((delta / 1000L) / 60L) / 60L;
                return (hours <= 0 ? 1 : hours) + "小时前";
            }
            SimpleDateFormat sdfRes = new SimpleDateFormat(FORMAT_ONE, defLocale);
            return sdfRes.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return dateStr;
        }
    }

    /**
     * 格式化相对时间【1小时以内（不含1小时），显示**分钟前，24小时以内（不含24小时），显示**小时前，1天以上（含1天），显示YYYY-MM-DD HH:mm】
     *
     * @param dateStr 时间字符串
     * @return 格式化后的时间字符串
     */
    public static String formatReleaseMinute(String dateStr) {
        if (EmptyUtil.isEmpty(dateStr)) {
            return "";
        }
        if (dateStr.contains(".")) {
            dateStr = dateStr.substring(0, dateStr.indexOf("."));
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_THREE, defLocale);
            Date date = sdf.parse(dateStr);
            if (date == null) {
                return dateStr;
            }
            long delta = new Date().getTime() - date.getTime();
            if (delta < 60L * 60000L) {
                long minutes = (delta / 1000L) / 60L;
                return (minutes <= 0 ? 1 : minutes) + "分钟前";
            }
            if (delta < 24L * 3600000L) {
                long hours = ((delta / 1000L) / 60L) / 60L;
                return (hours <= 0 ? 1 : hours) + "小时前";
            }
            SimpleDateFormat sdfRes = new SimpleDateFormat(FORMAT_TWO, defLocale);
            return sdfRes.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return dateStr;
        }
    }

    /**
     * 格式化相对时间【1小时以内（不含1小时），显示**分钟前，24小时以内（不含24小时），显示**小时前，1天以上（含1天），显示YYYY-MM-DD HH:mm:ss】
     *
     * @param dateStr 时间字符串
     * @return 格式化后的时间字符串
     */
    public static String formatReleaseSecond(String dateStr) {
        if (EmptyUtil.isEmpty(dateStr)) {
            return "";
        }
        if (dateStr.contains(".")) {
            dateStr = dateStr.substring(0, dateStr.indexOf("."));
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_THREE, defLocale);
            Date date = sdf.parse(dateStr);
            if (date == null) {
                return dateStr;
            }
            long delta = new Date().getTime() - date.getTime();
            if (delta < 60L * 60000L) {
                long minutes = (delta / 1000L) / 60L;
                return (minutes <= 0 ? 1 : minutes) + "分钟前";
            }
            if (delta < 24L * 3600000L) {
                long hours = ((delta / 1000L) / 60L) / 60L;
                return (hours <= 0 ? 1 : hours) + "小时前";
            }
            SimpleDateFormat sdfRes = new SimpleDateFormat(FORMAT_THREE, defLocale);
            return sdfRes.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return dateStr;
        }
    }

    /**
     * 格式化相对时间【1小时以内（不含1小时），显示**分钟前，24小时以内（不含24小时），显示**小时前，1天以上（含1天），显示HH:mm:ss】
     *
     * @param dateStr 时间字符串
     * @return 格式化后的时间字符串
     */
    public static String formatReleaseTime(String dateStr) {
        if (EmptyUtil.isEmpty(dateStr)) {
            return "";
        }
        if (dateStr.contains(".")) {
            dateStr = dateStr.substring(0, dateStr.indexOf("."));
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_THREE, defLocale);
            Date date = sdf.parse(dateStr);
            if (date == null) {
                return dateStr;
            }
            long delta = new Date().getTime() - date.getTime();
            if (delta < 60L * 60000L) {
                long minutes = (delta / 1000L) / 60L;
                return (minutes <= 0 ? 1 : minutes) + "分钟前";
            }
            if (delta < 24L * 3600000L) {
                long hours = ((delta / 1000L) / 60L) / 60L;
                return (hours <= 0 ? 1 : hours) + "小时前";
            }
            SimpleDateFormat sdfRes = new SimpleDateFormat(FORMAT_THREE, defLocale);
            String time = sdfRes.format(date);
            return time.substring(time.lastIndexOf(' '));
        } catch (ParseException e) {
            e.printStackTrace();
            return dateStr;
        }
    }


    /**
     * 格式化礼物时间
     *
     * @param startTime 开始时间
     * @param sysTime   系统时间
     * @return 格式化礼物时间
     */
    public static String[] formatTimer(String startTime, long sysTime) {
        String[] time = null;
        if (startTime.contains(".")) {
            startTime = startTime.substring(0, startTime.indexOf("."));
        }
        try {
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", defLocale);
            Date startDate = sdf2.parse(startTime);
            Date sysDate = new Date(sysTime);
            if (sysTime >= startDate.getTime()) {
                time = new String[]{"00", "00", "00"};
            } else {
                long dt = startDate.getTime() - sysDate.getTime();
                long h = dt / (60 * 60 * 1000);
                long m = (dt / (60 * 1000)) - (h * 60);
                long s = (dt / 1000) - (h * 60 * 60) - (m * 60);
                time = new String[]{h < 10 ? "0" + h : "" + h, m < 10 ? "0" + m : "" + m, s < 10 ? "0" + s : "" + s};
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    private static int judgeDate(Date date) {
        Calendar calendarToday = Calendar.getInstance();
        calendarToday.set(Calendar.HOUR_OF_DAY, 0);
        calendarToday.set(Calendar.MINUTE, 0);
        calendarToday.set(Calendar.SECOND, 0);
        calendarToday.set(Calendar.MILLISECOND, 0);

        Calendar calendarYesterday = Calendar.getInstance();
        calendarYesterday.add(Calendar.DAY_OF_MONTH, -1);
        calendarYesterday.set(Calendar.HOUR_OF_DAY, 0);
        calendarYesterday.set(Calendar.MINUTE, 0);
        calendarYesterday.set(Calendar.SECOND, 0);
        calendarYesterday.set(Calendar.MILLISECOND, 0);

        Calendar calendarLastYear = Calendar.getInstance();
        calendarLastYear.set(Calendar.MONTH, 0);
        calendarLastYear.set(Calendar.DAY_OF_MONTH, 0);
        calendarLastYear.set(Calendar.HOUR_OF_DAY, 23);
        calendarLastYear.set(Calendar.MINUTE, 59);
        calendarLastYear.set(Calendar.SECOND, 59);
        calendarLastYear.set(Calendar.MILLISECOND, 0);

        Calendar calendarTarget = Calendar.getInstance();
        calendarTarget.setTime(date);

        if (calendarTarget.before(calendarYesterday)) {
            if (calendarTarget.before(calendarLastYear)) {
                return lastYear;
            }
            return beforeYesterday;
        }
        if (calendarTarget.before(calendarToday)) {
            return yesterday;
        }
        return today;
    }

    private static String fromatDate(Date date, String fromat) {
        SimpleDateFormat sdf = new SimpleDateFormat(fromat, defLocale);
        return sdf.format(date);
    }
}
